import React, { useEffect, useState } from 'react';
import { connect } from 'dva';
import { history } from 'umi';
import { Tabs, Tree, Button, Spin, Table, Radio, message } from 'antd';
import ColumnCollapse from '@/components/ColumnCollapse';
import CustomDatePicker from '@/components/CustomDatePicker';
import Loading from '@/components/Loading';
import { downloadExcel } from '@/utils/array';
import XLSX from 'xlsx';
import style from '@/pages/IndexPage.css';

function CostReport({ dispatch, user, fields, cost }){
    const { authorized } = user;
    const { allFields, energyTypes, currentEnergy, treeLoading, allFieldAttrs, currentField, currentAttr, expandedKeys  } = fields;
    const { costData, currentPage, total, dataType, isLoading } = cost;
    useEffect(()=>{
        if ( authorized ) {
            new Promise((resolve, reject)=>{
                dispatch({ type:'fields/init', payload:{ resolve, reject }})
            })
            .then(()=>{
                dispatch({ type:'cost/fetchCostReport' });
            })
        }
    },[authorized])
    const items = allFields.map(( item, index)=>{
        return { 
            label:item.typeName, 
            key:item.energyType,
            children:(           
                item.energyFieldList && item.energyFieldList.length 
                ?
                <Tabs
                    className={style['custom-tabs']}
                    type='card'
                    onChange={activeKey=>{
                        let temp = item.energyFieldList.filter(i=>i.fieldId === activeKey)[0];
                        dispatch({ type:'fields/setCurrentField', payload:temp });
                        new Promise((resolve, reject)=>{
                            dispatch({ type:'fields/fetchFieldAttrs', payload:{ resolve, reject }});
                        })
                        .then((fieldAttrs)=>{
                            dispatch({ type:'cost/fetchCostReport' });
                        })
                    }}
                    items={item.energyFieldList.map(field=>{
                        return {
                            label:field.fieldName,
                            key:field.fieldId,
                            children:(
                                treeLoading
                                ?
                                <Spin className={style['spin']} />
                                :
                                <Tree
                                    className={style['custom-tree']}
                                    expandedKeys={expandedKeys}
                                    onExpand={temp=>{
                                        dispatch({ type:'fields/setExpandedKeys', payload:temp });
                                    }}
                                    selectedKeys={[currentAttr.key]}
                                    treeData={allFieldAttrs[currentField.fieldId]}
                                    onSelect={(selectedKeys, { node })=>{
                                        dispatch({type:'fields/setCurrentAttr', payload:node });
                                        dispatch({ type:'cost/fetchCostReport' });
                                    }}
                                />
                            )
                        }
                    })}
                />
                :
                <div style={{ padding:'1rem'}}>
                    <div className={style['text']} >当前能源类型还没有设置维度</div>
                    <div style={{ marginTop:'1rem' }}><Button type="primary" onClick={()=>{
                        history.push('/info_manage/field_manage');
                    }}>添加维度</Button></div>
                </div>                
            )
        }
    })
    let energyInfo = energyTypes[currentEnergy] || {};
    const sidebar = (
        <div className={style['card-container']}>        
            <Tabs
                className={style['custom-tabs']}
                items={items}
                activeKey={currentEnergy}
                onChange={activeKey=>{
                    dispatch({ type:'fields/setEnergyType', payload:activeKey });
                    let temp = allFields.filter(i=>i.energyType === activeKey)[0];
                    let field = temp.energyFieldList && temp.energyFieldList.length ? temp.energyFieldList[0] : {};
                    dispatch({ type:'fields/setCurrentField', payload:field });
                    // 更新不同能源的维度属性树
                    new Promise((resolve, reject)=>{
                        dispatch({ type:'fields/fetchFieldAttrs', payload:{ resolve, reject }});
                    })
                    .then((fieldAttrs)=>{
                        dispatch({ type:'cost/fetchCostReport' });
                    })
                }}                
            /> 
        </div>
    );
    const dateColumns = costData.length ? costData[0].dateList : [];
    const columns = [
        { title:'序号', dataIndex:'order', render:(text, record, index)=>{ return (currentPage - 1) * 12 + index + 1 }},
        { title:'属性', dataIndex:'attrName' },
        { title:'能源类型', render:()=>{ return energyInfo.typeName || '' }},
        { title:'能源单位', render:()=>{ return energyInfo.unit || '' }},
        { title: dataType === 1 ? '成本汇总' : '能耗汇总', dataIndex:'totalCost' },
        ...dateColumns.map((item, i)=>({ title:item, width:'80px', dataIndex:'dateDataList', render:arr=>arr[i] || '--' }))
    ]
    const content = (     
        <div style={{ height:'100%', position:'relative' }}>
            { isLoading && <Loading /> }
            <div style={{ height:'40px', display:'flex', justifyContent:'space-between' }}>
                <div style={{ display:'flex' }}>
                    <Radio.Group className={style['custom-radio']} style={{ marginRight:'1rem' }} value={dataType} onChange={e=>dispatch({ type:'cost/setDataType', payload:e.target.value })}>
                        <Radio.Button value={1}>成本</Radio.Button>
                        <Radio.Button value={5}>能耗</Radio.Button>
                    </Radio.Group>
                    <CustomDatePicker onDispatch={()=>dispatch({ type:'cost/fetchCostReport' })} />
                </div>
                <Button type='primary' onClick={()=>{
                    if ( costData.length ) {
                        // 请求全部数据源
                        new Promise((resolve, reject)=>{
                            dispatch({ type:'cost/fetchCostReport', payload:{ resolve, reject, pageSize:9999 }})
                        })
                        .then((data)=>{
                            let fileTitle = '成本报表';
                            var aoa = [], thead = [];
                            columns.forEach(i=>thead.push(i.title));
                            aoa.push(thead);
                            data.forEach((item,index)=>{
                                let temp = [];
                                temp.push(index + 1);
                                temp.push(item.attrName);
                                temp.push(energyInfo.typeName || '');
                                temp.push(energyInfo.unit || '');
                                temp.push(item.totalCost);
                                dateColumns.forEach((time, i)=>{
                                    temp.push(item.dateDataList[i] || '--');
                                })                       
                                aoa.push(temp);
                            });
                            var sheet = XLSX.utils.aoa_to_sheet(aoa);
                            sheet['!cols'] = thead.map(i=>({ wch:16 }));
                            downloadExcel(sheet, fileTitle + '.xlsx' );                         
                        })
                        
                    } else {
                        message.info('数据源为空');
                    }
                }}>导出报表</Button>
            </div>
            <div className={style['card-container']} style={{ height:'calc( 100% - 40px)'}}>
                <Table
                    dataSource={costData}
                    bordered={true}
                    rowKey='attrId'
                    className={style['self-table-container']}
                    columns={columns}
                    scroll={{ x:'1000px' }}
                    locale={{ emptyText:(<div style={{ margin:'1rem 0'}}>成本报表为空</div>) }}
                    pagination={{ total, current:currentPage, pageSize:12, showSizeChanger:false  }}
                    onChange={pagination=>{
                        dispatch({ type:'cost/fetchCostReport', payload:{ currentPage:pagination.current }})
                    }}
                />
            </div>
        </div>
    );
   
    return <ColumnCollapse sidebar={sidebar} content={content} />
}

export default connect(({ user, fields, cost })=>({ user, fields, cost }))(CostReport);